// Two function need to be implemented , mindex_handler & mindex_handler_configMode
// used GM Variables
// ds_buildingRuleCurrent : for identify the what building need to be built.
// ds_taxCollected_+ds_currentCityID : identity for determine whether tax has been collected.
// ds_currentCityID : identity for current city ID.
// ds_marketRuleStep : 进行到哪一步  fir、buy sec、sale sec、buy th、sale th..
// ds_marketRuleTryCount : 买卖失败后的重试次数.

//multi city management.
//get the current city id & index before do anythings.
var currentCityID = 0;
var currentCityName = jQuery.trim($("div.city_name > h1 ").html().replace(/(<([^>]+)>)/ig,"").replace(/\(.*\)/ig,""));
var citys = [];//city objects array,it's html object array
var currentCityIndex = 0;//current city index
citys = $x("//div[@class='col1']/div[@class='my_citys']/ul/li");
//find out the currentCityIndex
for(var i=0;i<citys.length;i++){
    var src = citys[i].childNodes[0].childNodes[0].getAttribute("src");
    if(src.indexOf("_on.gif")>-1){
        currentCityIndex = i;
        var link = citys[i].childNodes[0].getAttribute("href");
        currentCityID = link.substring(link.indexOf("vid=")+4);
        break;
    }
}
GM_safeVariables['ds_currentCityID'] = currentCityID;

function mindex_handler(){
    //generate UI for ignore city rules
    //{id:"1111",cityName:"屠龙者主城"} 
    var ignoreCityRule = CONFIG.ignore_cityRules.getObjectByProperty('cityName',currentCityName);
    if(ignoreCityRule != null){
        $('div.city_name > h1 ').append('<span style="margin-left:10px;font-size:14px;">'+getDSIconPath()+'屠龍者將忽略當前城市</span>');
    }else{
        $('div.city_name > h1 ').append('<span style="margin-left:10px;font-size:14px;">'+getDSIconPath()+'屠龍者將管理當前城市</span>');
    }
    //generate UI for building list.
    var buildingRules = _getBuildingRulesByCity(currentCityName);
    if(buildingRules.length > 0){
        if($('ul.bd_info').length > 0){
            $('ul.bd_info').after('<ul class="ds_bd_info bd_info"></ul>');
        }else{
            $('ul.hero_info').before('<ul class="ds_bd_info bd_info"></ul>');
        }

        $('ul.ds_bd_info')
        .append('<li>'+getDSIconPath()+'屠龍者建筑隊列</li>');
        for(var i = 0;i<buildingRules.length;i++){
            var buildingRule = buildingRules[i];
            $('ul.ds_bd_info').append('<li>(隊列中) '+buildingRule.buildingName+'</li>');
        }
    }
    //ignore city by ignore city rules
    if(ignoreCityRule != null){
        //start to switch city logic code.
        if(currentCityIndex == (citys.length - 1)){
            currentCityIndex = 0;
        }else{
            currentCityIndex++;
        }
        var nextCityName = citys[currentCityIndex].childNodes[0].getAttribute("title");
        var link = citys[currentCityIndex].childNodes[0].getAttribute("href");
        log("由于規則限制，忽略當前城市'"+currentCityName+"',跳轉到下個城市'"+nextCityName+"'...");
        clickLink(link);
        return;
    }
	
	//auto hunt
    if(CONFIG.hunt_rules.length > 0 && $('ul.hero_info > li > h3').length > 1){
        var nameH3 = $('ul.hero_info > li > h3');
        for(var i=0;i<CONFIG.hunt_rules.length;i++){
            var huntRule = CONFIG.hunt_rules[i];
            var existsAllHero = true;
            for(var j=0;j<huntRule.heros.length;j++){
                var hero = huntRule.heros[j];
                var existsHeroj = false;
                for(var k=0;k<nameH3.length;k++){
                    var name = nameH3.get(k).innerHTML;
                    if(name.indexOf(hero.name) > -1){
                        existsHeroj = true;
                        break;
                    }
                }
                existsAllHero = existsAllHero && existsHeroj;
            }
            if(existsAllHero == true){
                // set current rule for hunt, jump to map page.
                var strHeroName = '';
                for(var m=0;m<huntRule.heros.length;m++){
                    var objHero = huntRule.heros[m];
                    strHeroName += objHero.name + ',';
                }
                log('找到對應與英雄"'+strHeroName+'"的狩獵規則,跳轉到地圖頁面...');
                //分配士兵
                var armys = $x("//ul[@class='hero_info']/li/a/img[@src='/sys/images/hero_none.gif']")[0].parentNode.parentNode;
                if((CONFIG.enable_armyRules == true)&& armys.getElementsByTagName('div').length>0
      						&& GM_safeVariables["ds_lastArmyAssignmentedHour_"+window.location.host+GM_getValue("ds_currentCityID")] != (new Date().getHours().toString())&& CONFIG.army_rules.length > 0){
        					log("英雄准备出征,正在準備軍隊分配...");
       						GM_safeVariables["ds_armyAssignmented_"+window.location.host+GM_getValue("ds_currentCityID")]="";
							clickLink('/s2h');
        					return;
        					}
        		//分配士兵结束
                GM_safeVariables["ds_huntRuleCurrent"] = uneval(huntRule);
                if(!huntRule.isPointing) {
                    clickLink('/GameMap');
                    return
                }else {
                    var linkName = huntRule.attackName;
                    var rmid = -1;
                    for(var i=0;i<CONFIG.attackList.length;i++){
                        if(CONFIG.attackList[i].names == linkName){
                            rmid = i;
                            break;
                        }
                    }
                    if(rmid != -1){
                        clickLink(CONFIG.attackList[rmid].urls);
                        return;
                    }
                }
            }
        }
    }
    //auto building
    if(CONFIG.building_rules.length > 0){
        //alert($('ul.bd_info:not(ul.ds_bd_info) > li').length);
        //var uls = $x("//ul[@class='bd_info']/li");
        var uls = $('ul.bd_info:not(ul.ds_bd_info) > li');
        if(uls.length < 2){ // when the server building queue is empty,do the next building in ds' queue//lixiao
            if(buildingRules.length == 0){ // no match building rule for current city
                log("沒有針對當前城市的建筑規則...");
            }else{
                //code for get wether exists the building of current rule,if exists just upgrading...
                var rule = buildingRules[0]; 
                if(rule.buildingName == '' || rule.buildingName == null){
                    log("當前執行的建筑步驟中的建筑物名稱為空,取消建筑并刪除當前步驟...");
                    CONFIG.building_rules.removeByObjectProperty("id",rule.id);
                    clickLink("/mindex");
                    return;
                }else{
                    var areas = _getAreasByBuildingName(rule.buildingName);
                    var link = '';
                    if(areas.length == 0){
                        log("不存在當前建造,步驟中指定的建筑'"+rule.buildingName+"',進入該建筑的建造流程...");
                        areas = _getAreasByBuildingName("空地");
                        if(areas.length == 0){
                            log("您城中不存在當前建筑'"+rule.buildingName+"',同時已經沒有可以建筑的空地,證明當期指定的建筑步驟有誤，取消建造并刪除當前步驟...");
                            CONFIG.building_rules.removeByObjectProperty("id",rule.id);
                            clickLink("/mindex");
                            return;
                        }
                    }else{
                        log("已經存在當前建造步驟中制定的建筑'"+rule.buildingName+"',進入該建筑的升級流程...");
                    }
                    //GM_setValue("ds_buildingRuleCurrent_"+window.location.host,uneval(rule));
                    GM_safeVariables["ds_buildingRuleCurrent"] = rule;
                    clickLink(areas[0].getAttribute("href"));
                    return;
                }
            }
        }else{
            log("當前建筑隊列已滿,無法進行任何建筑操作");
        }
    }
    //detect new messages,if new messages arrived , modify the open messagebox link to open unread message list.
	if(CONFIG.auto_read=='true'){// auto read messagebox
		var msgs = $('img[src="/sys/images/msg1.gif"]');
		if(msgs.length > 0){
			//log("發現未讀新消息,但是心情不好,懶得進去看,等下次再看吧...");
			if(makeDecision(0.5)){
				msgs.parent().attr('href','/messageList?type=1&isread=0');
				log("發現未讀新消息,進入消息閱讀處理流程...");
				clickLink("/messageList?type=1&isread=0");
				return;
			}
		}
	}
    //将进入市场的几率暂时定为30%
    //alert(CONFIG.market_rules.decisionpercent);
    if(makeDecision(CONFIG.market_rules.decisionpercent)){
        log("進入市場處理流程...");
        var areas = _getAreasByBuildingName("市場");
        if(areas.length == 0){
            log("您的城市居然沒有市場？被雷到了！");
        }else{
            //如果没有定制自动售卖规则，则不进入市场流程
            if (CONFIG.market_rules.isautobuy || CONFIG.market_rules.isautosale) {
                log("發現市場,進入市場處理流程");
                GM_safeVariables["ds_marketRuleStep"] = "fir";
                GM_safeVariables["ds_marketRuleTryCount"] = "0";
                clickLink("/market");
                return;
            }
        }
    };
    //open Inn to resurrect heros, probability = 50%
    if(CONFIG.auto_resurrect == true && makeDecision(0.2) ){
        var areas = _getAreasByBuildingName("酒館");
        if(areas.length == 0){
            log("您允許自動復活英雄,但無法找到酒館為您復活英雄，請建造一個酒館...");
        }else{
            log("您允許自動復活英雄并發現酒館，進入酒館進行英雄復活...");
            clickLink(areas[0].getAttribute('href'));//transition to state resurrect hero.
            return;
        }
    }
    //collect tax
    //if(GM_getValue("ds_taxCollected_"+window.location.host+GM_getValue("ds_currentCityID")) != (new Date()).toLocaleDateString()){
    if(GM_safeVariables["ds_taxCollected_"+GM_safeVariables['ds_currentCityID']] != (new Date()).toLocaleDateString()){
        var areas = _getAreasByBuildingName("市政中心");
        if(areas.length == 0){
            log("您的城市居然沒有市政中心？被雷到了！");
        }else{
            log("發現市政中心，進入市政中心處理");
            clickLink(areas[0].getAttribute('href'));//transition to state resurrect hero.
            return;
        }
    }
	//回城
	/*war_info = $("ul[@class='war_info']>li");
	for(i=1;i<=war_info.length;i++){
		war_status =$("ul[@class='war_info']>li>a").next().html();
		if(war_status!='&gt;&gt;1'){//返程的路上
			needTimer = $("#t"+i).html();
			if(parseInt(needTimer.split(":")[1])!=parseInt(0)){
				console.log('the hero back to the city for too long, by drilling into the membership process to the city');
				clickLink("/building?tid=15");
				return;
			}
		}else{
			needTimer = $("#t"+i).html();
			alert(needTimer);
		}
	}*/
	
	//auto gamble
	if(CONFIG.auto_gamble == true && GM_safeVariables["ds_gambleOver_"+window.location.host] != (new Date()).toLocaleDateString()){   
      log("今天還沒有去過賭館,手癢了,去看看...");
      clickLink("/gdpf");//transition to state resurrect hero.
      return;
    }

    //jump to next city logic
    //start to switch city logic code.
    if(citys.length > 1){
        if(currentCityIndex == (citys.length - 1)){
            currentCityIndex = 0;
        }else{
            currentCityIndex++;
        }
        var cityName = citys[currentCityIndex].childNodes[0].getAttribute("title");
        var link = citys[currentCityIndex].childNodes[0].getAttribute("href");
        log("當前城市的邏輯已經處理完成,等待1分鐘左右跳轉到下個城市'"+cityName+"'...");
        var randomTime = Math.random()*60000;
        randomTime = randomTime<10000?10000:randomTime;
        window.setTimeout(function(){
            window.location.href = link;
        },randomTime);
        return;
    }

	
    //nothing logic for action
    //stay at index page and keep checking the conditions 
    log("未發現任何需要處理的邏輯");
    var randomTime = Math.random()*600000;
    randomTime = randomTime<300000?300000:randomTime;
    window.setTimeout('window.location.href=""',randomTime);
}


function mindex_handler_configMode(){
    //为了尊重作者个人的努力,请您不要去掉这个广告代码.如果您有这些精力找到这段广告代码的话,为什么不去研究点实际的功能呢?如果您确实去掉了这段广告代码的话,请通知我,并且请不要将修改后的代码进行传播.多谢您的支持.
    //code for google adsense
    //$('div.col3 > h2:first').before('<h2>屠龙者插件</h2><div style="z-index:999999"><iframe frameborder="0" width="165" height="620" scrolling="no" src="http://qilongjitools.cn/asdscripts/ds_ad.html" /></div>');
    $('div.container > div.col1').append('<div style="z-index:999999"><iframe frameborder="0" width="470" height="62" scrolling="no" src="http://qilongjitools.cn/asdscripts/dswave_horizontal.html" /></div>');
    
    //code for ignore city rules
    //{id:"1111",cityName:"屠龙者主城"}
    $('div.city_name > h1 ').append('<span style="margin-left:10px;font-size:14px;">'+getDSIconPath()+'<input type="checkbox" class="ds_cfg_chkIgnoreCity" checked />委托屠龍者管理此城市</span>');
    var ignoreCityRule = CONFIG.ignore_cityRules.getObjectByProperty('cityName',currentCityName);
    if(ignoreCityRule != null){
        $('div.city_name > h1 > span > input.ds_cfg_chkIgnoreCity').get(0).checked = false;
    }else{
        $('div.city_name > h1 > span > input.ds_cfg_chkIgnoreCity').get(0).checked = true;
    }
    $('div.city_name > h1 > span > input.ds_cfg_chkIgnoreCity').click(function(){
        if(this.checked == false){
            var id = new Date().getTime();
            var rule = new Object();
            rule.id = id;
            rule.cityName = currentCityName;
            CONFIG.ignore_cityRules.push(rule);
        }else{
            CONFIG.ignore_cityRules.removeByObjectProperty('cityName',currentCityName);
        }
    });
    //code for auto building rules
    if($('ul.bd_info').length > 0){
        $('ul.bd_info').after('<ul class="ds_bd_info bd_info"></ul>');
    }else{
        $('ul.hero_info').before('<ul class="ds_bd_info bd_info"></ul>');
    }
    $('ul.ds_bd_info')
    .append('<li>'+getDSIconPath()+'委托屠龍者為您建造<input type="text" class="ds_cfg_buildingCityName" value="" style="width:60px;margin-left:4px;margin-right:4px;"/><a class="ds_cfg_addBuildingRule" href="javascript:{void(0);}">增加</a></li>');
    var createItem = function(rule){
        $('ul.ds_bd_info').append('<li><a id="'+rule.id+'" class="ds_removeBulding" onclick="javascript:{void(0)}" href="javascript:{void(0)}"><img src="/sys/images/del.gif"/></a> '+rule.buildingName+'</li>');
        $('ul.ds_bd_info > li:last > a.ds_removeBulding').click(function(){
            $ID(rule.id).parentNode.parentNode.removeChild($ID(rule.id).parentNode);
            var rmIdx = -1;
            for(var i=0;i<CONFIG.building_rules.length;i++){
              if(CONFIG.building_rules[i].id == rule.id){
                rmIdx = i;
                break;
              }
            }
            if(rmIdx != -1)
              CONFIG.building_rules.remove(rmIdx);
        })
    }
    $('a.ds_cfg_addBuildingRule').click(function(){
        var id = new Date().getTime();
        var rule = new Object();
        rule.id = id;
        rule.cityName = currentCityName;
        rule.buildingName = $("input.ds_cfg_buildingCityName").val();
        CONFIG.building_rules.push(rule);
        createItem(rule);
    })
    //generate building list.
    var buildingRules = _getBuildingRulesByCity(currentCityName);
    if(buildingRules.length > 0){
        for(var i = 0;i<buildingRules.length;i++){
            var buildingRule = buildingRules[i];
            createItem(buildingRule);
        }
    }
    
    return;

}

//private utility function
var _getBuildingRulesByCity = function(cityName){
    var res = []
    for(var i=0;i<CONFIG.building_rules.length;i++){
        var rule = CONFIG.building_rules[i];
        //console.log('cityName:'+cityName+',rule.cityName:'+rule.cityName+',rule.buildingName:'+rule.buildingName);
        if(cityName.indexOf(rule.cityName) > -1){
            res.push(rule);
        }
    }
    return res;
}

var _getAreasByBuildingName = function(buildingName){
    var areaTags = document.getElementsByTagName("area");
    var areas = [];
    for(var i=0;i<areaTags.length;i++){
        var name = areaTags[i].getAttribute('title').trim();
        if (buildingName == '石頭礦') {
            buildingName = '採石場';
        }
        var _name = buildingName;
        if(name.startWith(buildingName)) {
            areas.push(areaTags[i]);
        }
        
    }
    return areas;
}
